package com.glsc.ngateway.platform.service.system;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.glsc.ngateway.common.api.common.enums.DictConstant;
import com.glsc.ngateway.common.base.domain.mysql.gateway.system.GwContact;
import com.glsc.ngateway.common.base.domain.mysql.gateway.system.SystemVendorContractRelation;
import com.glsc.ngateway.common.base.domain.mysql.gateway.system.SystemVendorInfo;
import com.glsc.ngateway.common.api.platform.dto.system.ParamSystemVendorInfoDto;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.it.ItApplicationDetailRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.it.ItOperationRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.it.ItVirtualDeviceRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.system.GwContractRepository;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.system.SystemVendorContractRelationRepository;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.system.SystemVendorInfoRepository;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.system.SystemVendorLogInfoRepository;
import com.glsc.ngateway.platform.service.MailService;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.platform.service.it.SequenceService;
import com.glsc.ngateway.platform.service.it.ServerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class SystemVendorInfoService {

    Logger logger = LoggerFactory.getLogger(SystemVendorInfoService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private UserService userService;
    @Autowired
    private ItVirtualDeviceRepo itVirtualDeviceRepo;
    @Autowired
    private ItOperationRepo itOperationRepo;
    @Autowired
    private ItApplicationDetailRepo itApplicationDetailRepo;

    @Autowired
    private ServerService serverService;

    @Autowired
    private MailService mailService;

    @Resource
    private SystemVendorInfoRepository systemVendorInfoRepository;
    @Resource
    private GwContractRepository gwContractRepository;
    @Resource
    private SystemVendorLogInfoRepository systemVendorLogInfoRepository;
    @Resource
    private SystemVendorContractRelationRepository systemVendorContractRelationRepository;

    @Transactional
    public void addOrUpdate(SystemVendorInfo systemVendorInfo) {
        if (systemVendorInfo.getId() != null) {
            //修改的情况下需要先删除联系人
            systemVendorContractRelationRepository.deleteByVendorIdAndContactType(systemVendorInfo.getId(), DictConstant.CONTRACT_VENDOR);
        }

        systemVendorInfo.setDeleted(DictConstant.NO_DELETE);
        systemVendorInfoRepository.save(systemVendorInfo);
        if (StrUtil.isEmpty(systemVendorInfo.getVendorCode())) {
            String vendorCode = "GLVENDOR" + String.format("%04d", systemVendorInfo.getId());
            systemVendorInfo.setVendorCode(vendorCode);
            systemVendorInfoRepository.save(systemVendorInfo);
        }
        if (CollectionUtil.isNotEmpty(systemVendorInfo.getVendorContractId())) {
            List<SystemVendorContractRelation> list = systemVendorInfo.getVendorContractId().stream().map(
                    e -> {
                        SystemVendorContractRelation relation = new SystemVendorContractRelation();
                        relation.setVendorId(systemVendorInfo.getId());
                        relation.setContactType(DictConstant.CONTRACT_VENDOR);
                        relation.setContactId(e);
                        return relation;
                    }
            ).collect(Collectors.toList());
            systemVendorContractRelationRepository.saveAll(list);
        }
//        systemVendorLogInfoRepository.save(log);
    }

    public void delete(String code) {
        SystemVendorInfo bean = systemVendorInfoRepository.queryFirstById(Integer.valueOf(code));
        bean.setDeleted(DictConstant.DELETED);
//        SystemVendorLogInfo log = new SystemVendorLogInfo();
//        BeanUtil.copyProperties(bean,log);
//        log.setLogFlag(DictConstant.DELETE);

        systemVendorInfoRepository.save(bean);
//        systemVendorLogInfoRepository.save(log);
    }

    public Page<SystemVendorInfo> search(ParamSystemVendorInfoDto params) {
        Pageable pageable = PageRequest.of(params.getPageNo() - 1, params.getPageSize());
        params.setDeleted(DictConstant.NO_DELETE);
        Page<SystemVendorInfo> result = systemVendorInfoRepository.searchByParam(pageable, params);
        if (CollectionUtil.isNotEmpty(result)) {

            for (SystemVendorInfo vendorInfo : result) {
                //填充供应商
                List<SystemVendorContractRelation> systemVendorRelation = systemVendorContractRelationRepository.queryAllByVendorIdAndContactType(vendorInfo.getId(), DictConstant.CONTRACT_VENDOR);
                List<Integer> contractIds = systemVendorRelation.stream().map(v -> v.getContactId()).collect(Collectors.toList());
                vendorInfo.setVendorContractId(contractIds);
                //填充联系人
                if (CollectionUtil.isNotEmpty(contractIds)) {
                    List<GwContact> contracts = gwContractRepository.findAllByIdIn(contractIds);
                    if (CollectionUtil.isNotEmpty(contracts)) {
                        vendorInfo.setVendorContractName(contracts.stream().map(c -> c.getContactPerson()).collect(Collectors.toList()));
                        vendorInfo.setVendorContract(contracts);
                    }
                }
            }
        }
        return result;
    }

//    public List<SystemVendorLogInfo> queryLog(ParamSystemVendorInfoDto param) {
//        List<SystemVendorLogInfo> result = systemVendorLogInfoRepository.searchByParam(param);
//        return result;
//    }

    public Optional<SystemVendorInfo> findById(Integer id) {
        return systemVendorInfoRepository.findById(id);
    }


    public SystemVendorInfo findByCode(String code) {
        SystemVendorInfo condition = new SystemVendorInfo();
        condition.setVendorCode(code);
        List<SystemVendorInfo> list = systemVendorInfoRepository.findAll(Example.of(condition));
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

//
//
//    //虚拟机数据导出
//    public List<VirtualDeviceExport> queryVirtualOutPut(String svd) {
//        String condition = "";
//        if (svd != null) {
//            condition += " and ip1 like '%" + svd + "%' or ip2 like '%" + svd + "%' or mac1 like '%" + svd + "%' or mac2 like '%" + svd + "%' ";
//        }
////		if(machine!=null) {
////			condition+=" and machine="+machine;
////		}
//        String sql = "select op_name business_name, " +
//                "(select dict_value from t_dict c where c.zd_id = a.network_segment) network_segment, " +
//                "mx_name application_detail, " +
//                "case when a.machine_area=0 then '生产网' when a.machine_area=1 then '办公网' " +
//                "when a.machine_area=2 then '测试网' end machine_area, " +
//                "virtual_name, " +
//                "(select dict_value from t_dict f where f.zd_id = a.operation_sys) operation_sys, " +
//                "ip1,ip2,vcent_ip, " +
//                "(select dict_value from t_dict g where g.zd_id = a.cpu) cpu, " +
//                "(select dict_value from t_dict h where h.zd_id = a.memory) memory, " +
//                "(select ip1 from t_service_device j where j.dev_id = a.virtual_ip) virtual_ip, " +
//                "user_name user_id,department, " +
//                "case when a.qj=1 then 'Nutanix_Cluster' when a.qj=2 then 'MainCluster' " +
//                "when a.qj=3 then 'VMware_Cluster' when a.qj=4 then 'zbCluster' end qj, " +
////				     "(select dict_value from t_dict i where i.zd_id = a.qj) qj, " +               //20201207修复群集翻译问题
//                "case when mark=1 then '正常' when mark=2 then '已删除' end mark " +
//                "from t_virtual_device a " +
//                "left join t_operation b on a.business_name = b.op_id " +
//                "left join t_yinyong_detail d on a.application_detail = d.mx_id " +
//                "left join t_admin_user e on a.user_id = e.user_id where 1=1 " + condition;
//        return jdbcTemplate.query(sql, new VirtualRowMapper());
//    }
//
//    //虚拟机数据全部导出
//    public List<VirtualDeviceExportFull> queryVirtualFullOutPut(String svd) {
//        String condition = "";
//        if (svd != null) {
//            condition += " and ip1 like '%" + svd + "%' or ip2 like '%" + svd + "%' or mac1 like '%" + svd + "%' or mac2 like '%" + svd + "%' ";
//        }
////		if(machine!=null) {
////			condition+=" and machine="+machine;
////		}
//        String sql = "select op_name business_name, " +
//                "(select dict_value from t_dict c where c.zd_id = a.network_segment) network_segment, " +
//                "mx_name application_detail, " +
//                "case when a.machine_area=0 then '生产网' when a.machine_area=1 then '办公网' " +
//                "when a.machine_area=2 then '测试网' end machine_area, " +
//                "virtual_name, " +
//                "(select dict_value from t_dict f where f.zd_id = a.operation_sys) operation_sys, " +
//                "ip1,ip2,vcent_ip, " +
//                "(select dict_value from t_dict g where g.zd_id = a.cpu) cpu, " +
//                "(select dict_value from t_dict h where h.zd_id = a.memory) memory, " +
//                "(select ip1 from t_service_device j where j.dev_id = a.virtual_ip) virtual_ip, " +
//                "user_name user_id,bz,mac1,mac2,ip3,ip4,bf,department, " +
//                "case when a.qj=1 then 'Nutanix_Cluster' when a.qj=2 then 'MainCluster' " +
//                "when a.qj=3 then 'VMware_Cluster' when a.qj=4 then 'zbCluster' end qj, " +
////				     "(select dict_value from t_dict i where i.zd_id = a.qj) qj, " +                  //20201207修复群集翻译问题
//                "case when mark=1 then '正常' when mark=2 then '已删除' end mark " +
//                "from t_virtual_device a " +
//                "left join t_operation b on a.business_name = b.op_id " +
//                "left join t_yinyong_detail d on a.application_detail = d.mx_id " +
//                "left join t_admin_user e on a.user_id = e.user_id where 1=1 " + condition;
//        return jdbcTemplate.query(sql, new VirtualRowMapperFull());
//    }
//
//    public Map<String, Object> getInfo(String devId) {
//        Map<String, Object> conditions = new HashMap<String, Object>();
//        conditions.put("dev_id", devId);
//        return BeanUtil.underline2Camel(generalDataManager.queryForMap("t_virtual_device", conditions));
//    }
//
//    ///////////////////////////////////////
//    //查询虚拟主机IP页面（无需入参的范例）
//    public List<Map<String, Object>> queryMainIpByDevId(String devId) {
//        String sql = "select dev_id,ip1 from t_service_device";
//        //List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql, new Object[] {typeId});   测试看是否有数据
//        return BeanUtil.underline2Camel(jdbcTemplate.queryForList(sql, new Object[]{}));
//    }

}
